package com.pzl.library;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;

/**
 * Created by zl.peng on 2016-03-01.
 */
public class BeansIndicator extends View implements Indicator {
    private static final String TAG = "BeansIndicator";
    private ViewPager mViewPager;
    /**
     * 页数
     */
    private int mPagerAmount = 0;
    private int mRadius_Default;
    /**
     * 半径
     */
    private int mRadius;
    /**
     * 默认间距
     */
    private int mSpace_Default;
    /**
     * 间隔
     */
    private int mSpace;
    private int mBgColor_Default;
    private int mBgColor;
    private int mSelectedColor_Default;
    private int mSelectedColor;
    private int mWidth;
    private int mHeight;
    private float mPositionOffset;
    private int mCurrentPosition;
    private ArrayList<Rect> mRects;
    private Paint mPaint;

    public BeansIndicator(Context context) {
        this(context, null);
    }

    public BeansIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BeansIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        Resources res = getResources();
        mRadius_Default = res.getInteger(R.integer.BeansIndicator_Radius);
        mRadius = mRadius_Default;
        mSpace_Default = res.getInteger(R.integer.BeansIndicator_Space);
        mSpace = mSpace_Default;
        mBgColor_Default = res.getColor(R.color.BeansIndicator_BgColor);
        mBgColor = mBgColor_Default;
        mSelectedColor_Default = res.getColor(R.color.BeansIndicator_SelectedColor);
        mSelectedColor = mSelectedColor_Default;

        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.BeansIndicator, 0, 0);

        mRadius = (int) ta.getDimension(R.styleable.BeansIndicator_Radius, mRadius_Default);
        mSpace = (int) ta.getDimension(R.styleable.BeansIndicator_Space, mSpace_Default);
        mBgColor = ta.getColor(R.styleable.BeansIndicator_BgColor, mBgColor_Default);
        mSelectedColor = ta.getColor(R.styleable.BeansIndicator_SelectedColor, mSelectedColor);

        ta.recycle();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    @Override
    public void bindViewPager(ViewPager viewPager) {
        if (viewPager == null) throw new IllegalStateException("viewpager is null!");
        if (viewPager.getAdapter() == null)
            throw new IllegalStateException("please set viewpager adapter!");
        mViewPager = viewPager;
        mViewPager.addOnPageChangeListener(this);
        mPagerAmount = mViewPager.getAdapter().getCount();
    }


    /**
     * 计算indicatorTouch响应区域
     */
    private void initTouchAreas() {
        mRects = new ArrayList<Rect>();
        for (int i = 0; i < mPagerAmount; i++) {
            Rect rect = new Rect();
            rect.left = mWidth / 2 - (mPagerAmount * (mRadius * 2) + mSpace * (mPagerAmount - 1)) / 2 + mRadius + (2 * mRadius + mSpace) * i - mRadius;
            rect.top = mHeight / 2 - mRadius;
            rect.bottom = rect.top + 2 * mRadius;
            rect.right = rect.left + 2 * mRadius;
            mRects.add(rect);
            Log.i(TAG, "rect=" + rect.toString());
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mCurrentPosition = position;
        mPositionOffset = positionOffset;
        invalidate();
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        Log.i(TAG, "paramIn:widthMeasureSpec=" + widthSize + ",paramIn:heightMeasureSpec=" + heightSize);
        int width, height;
        if (mViewPager == null || widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            width = getPaddingLeft() + (mRadius * 2 * mPagerAmount) + (mSpace * (mPagerAmount - 1)) + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(width, widthSize);
            }
        }

        if (mViewPager == null || heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            height = getPaddingTop() + (mRadius * 2) + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightSize);
            }
        }
        setMeasuredDimension(width, height);
        Log.i(TAG, "after:MeasuredWidth=" + getMeasuredWidth() + ",after:MeasuredHeight=" + getMeasuredHeight());
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mWidth = getWidth();
        mHeight = getHeight();
        if (mRects == null) initTouchAreas();
        Log.i(TAG, "mWidth=" + mWidth + ",mHeight=" + mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mPagerAmount <= 0) return;
        /**
         * 背景
         */
        mPaint.setColor(mBgColor);
        for (int i = 0; i < mPagerAmount; i++) {
            canvas.drawCircle(mWidth / 2 - (mPagerAmount * (mRadius * 2) + mSpace * (mPagerAmount - 1)) / 2 + mRadius + (2 * mRadius + mSpace) * i, mHeight / 2, mRadius, mPaint);
        }

        mPaint.setColor(mSelectedColor);

        /**
         * 偏移
         */
        float xOffset = (2 * mRadius + mSpace) * mPositionOffset;
        canvas.drawCircle(mWidth / 2 - (mPagerAmount * (mRadius * 2) + mSpace * (mPagerAmount - 1)) / 2 + mRadius + (2 * mRadius + mSpace) * mCurrentPosition + xOffset, mHeight / 2, mRadius, mPaint);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent");
        if (mRects == null || mRects.size() == 0) return false;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            for (int i = 0; i < mRects.size(); i++) {
                Rect rect = mRects.get(i);
                if (rect.contains(x, y)) {
                    mViewPager.setCurrentItem(i);
                    break;
                }
            }
        }
        return true;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mViewPager == null) return;
        mViewPager.removeOnPageChangeListener(this);
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Log.i(TAG, "onSaveInstanceState");
        return super.onSaveInstanceState();
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        Log.i(TAG, "onRestoreInstanceState");
        super.onRestoreInstanceState(state);
    }
}
